package com.goldenautumn.prefabricate.activity.mine.order

import android.os.Bundle
import android.widget.TextView
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.SimpleItemAnimator
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPUtils
import com.goldenautumn.prefabricate.MainActivity
import com.goldenautumn.prefabricate.R
import com.goldenautumn.prefabricate.activity.cart.SettlementActivity
import com.goldenautumn.prefabricate.activity.mine.adapter.OrderItemAdapter
import com.goldenautumn.prefabricate.business.entity.GoodsInfoVO
import com.goldenautumn.prefabricate.business.entity.GoodsSkuVo
import com.goldenautumn.prefabricate.business.entity.OrderGoodsInfoVO
import com.goldenautumn.prefabricate.business.entity.OrderInfoVo
import com.goldenautumn.prefabricate.business.mall.GoodsInfoUiState
import com.goldenautumn.prefabricate.business.mall.MallViewModel
import com.goldenautumn.prefabricate.business.order.OrderListUiState
import com.goldenautumn.prefabricate.business.order.OrderStatusUiState
import com.goldenautumn.prefabricate.business.order.OrderViewModel
import com.goldenautumn.prefabricate.business.user.LoadingUiState
import com.goldenautumn.prefabricate.business.user.LoginUiState
import com.goldenautumn.prefabricate.business.user.UserViewModel
import com.goldenautumn.prefabricate.databinding.FragmentOrderListBinding
import com.goldenautumn.prefabricate.utils.Constants.BUSINESS_PAGE_DATA
import com.goldenautumn.prefabricate.utils.Constants.ORDER_TYPE_ALL
import com.goldenautumn.prefabricate.utils.Constants.ORDER_TYPE_SHIPMENT
import com.goldenautumn.prefabricate.utils.onCenterToast
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import kotlinx.coroutines.isActive
import kotlinx.coroutines.selects.select
import qncx.external.common.base.BaseFragment
import qncx.external.common.compat.gone
import qncx.external.common.compat.visible
import qncx.external.common.utils.intent
import qncx.external.common.widget.consecutive.ConsecutiveScrollerLayout.LayoutParams
import qncx.external.common.widget.dialog.PromptDialog
import qncx.external.common.widget.shapeview.shape.ShapeButton
import qncx.external.common.widget.view.TipsDialog

class OrderListFragment : BaseFragment<FragmentOrderListBinding>() {

    companion object {
        fun newInstance(type: String): OrderListFragment {
            val fragment = OrderListFragment()
            val bundle = Bundle()
            bundle.putString(BUSINESS_PAGE_DATA, type)
            fragment.arguments = bundle
            return fragment
        }
    }

    private val mOrderModel by viewModels<OrderViewModel>()

    private val mMallModel by viewModels<MallViewModel>()

    private val mAdapter by lazy {
        OrderItemAdapter()
    }

    private var page = 1

    private val orderType: String?
        get() = arguments?.getString(BUSINESS_PAGE_DATA, ORDER_TYPE_ALL)

    override fun getLayoutId(): Int = R.layout.fragment_order_list

    override suspend fun initView() {
        LogUtils.d("加载=$orderType")

        mBinding.orderRv.layoutManager = LinearLayoutManager(mContext)
        mBinding.orderRv.adapter = mAdapter
        (mBinding.orderRv.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
        mAdapter.setStateViewLayout(mContext,R.layout.recycler_empty_view)
        var msg = mAdapter.stateView?.findViewById<TextView>(R.id.prompt_content)
        var actionBtn = mAdapter.stateView?.findViewById<ShapeButton>(R.id.action_order)
        msg?.setText(R.string.not_order_msg)
        msg?.setCompoundDrawablesWithIntrinsicBounds(null, ContextCompat.getDrawable(mContext, R.mipmap.ic_empty_order), null, null)
        actionBtn?.visible()
        actionBtn?.setOnClickListener {
            SPUtils.getInstance().put("home",0)
            activity?.onBackPressedDispatcher?.onBackPressed()
        }
        mBinding.loading.appName.postDelayed({ mBinding.loading.appName.gone() }, 2000)

        mAdapter.setOnItemClickListener { adapter, _, position ->
            var item = adapter.getItem(position)
            startActivity(OrderDetailsActivity::class.intent.putExtra(BUSINESS_PAGE_DATA,item?.order_id))
        }

        mAdapter.addOnItemChildClickListener(R.id.actionBtnRight) { adapter, _, position ->
            var item = adapter.getItem(position)
            if(item?.order_status?.value == "10" && item?.pay_status?.value == "20" && item?.delivery_status?.value == "10") { //待发货取消
                setOrderCanCel(item,position)
            } else if(item?.order_status?.value == "10" && item?.pay_status?.value == "20" && item?.delivery_status?.value == "20") { //待收货查看物流
                onCenterToast("查看物流")
            } else if(item?.order_status?.value == "30" || item?.order_status?.value == "21" || item?.order_status?.value == "20" ) { //已完成再次购买
                addCarGoods(item.goods)
            } else startActivity(SettlementActivity::class.intent.putExtra("ORDER","${item?.order_id}")) //继续支付
        }

        mAdapter.addOnItemChildClickListener(R.id.actionBtnLeft) { adapter, _, position ->
            var item = adapter.getItem(position)
            if(item?.order_status?.value == "10" && item?.pay_status?.value != "20") { //待付款取消
                setOrderCanCel(item,position)
            }  else if (item?.order_status?.value == "10" && item?.pay_status?.value == "20" && item?.delivery_status?.value == "20") { //待收货售后
                onCenterToast("申请售后")
            }
        }

        mOrderModel.getOrderList(page,"$orderType")
        mBinding.refresh.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                page = 1
                mOrderModel.getOrderList(page,"$orderType")
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                mOrderModel.getOrderList(page,"$orderType")
            }
        })

        while (isActive) {
            select {
                mMallModel.goodsDetailsRequests.onReceive {
                    when (it) {
                        is GoodsInfoUiState.GoodsAddCar -> {
                            if(it.msg == null) addSuccess()
                            else onCenterToast(it.msg ?: "")
                        }
                        else -> {}
                    }
                }
                mOrderModel.loading.onReceive {
                    when (it) {
                        is LoadingUiState.LoadingUI -> {
                            if(!it.isShow) {
                                mBinding.refresh.finishRefresh()
                                mBinding.refresh.finishLoadMore()
                                mBinding.loading.appName.gone()
                                mAdapter.isStateViewEnable = true
                            } else {}
                        }
                        else -> {}
                    }
                }
                mOrderModel.orderListRequests.onReceive {
                    when (it) {
                        is OrderListUiState.OrderList -> {
                            mAdapter.submitList(it.orderList)
                            LogUtils.d("订单列表=${it.orderList}")
                        }
                        else -> {}
                    }
                }

                mOrderModel.orderStatusUiState.onReceive {
                    when (it) {
                        is OrderStatusUiState.ActionMsg -> {
                            if(it.msg != null) onCenterToast("${it.msg}")
                            else {
                                mAdapter.removeAt(it.position)
                                mAdapter.notifyItemChanged(it.position)
                            }
                        }
                        else -> {}
                    }
                }
            }
        }

    }

    fun setOrderCanCel(item:OrderInfoVo?,position:Int){
        PromptDialog().setConfirmListener(object : PromptDialog.ConfirmHandleListener {
            override fun bindView(dialog: PromptDialog, view: PromptDialog.PromptModel) {
                view.setMsgText(getString(R.string.cancel_order))
                view.setShowCancel(true)
                view.getPromptConfirm().setOnClickListener {
                    dialog.dismiss()
                    mOrderModel.onOrderCanCel("${item?.order_id}",position)
                }
            }
        }).onShow(childFragmentManager.beginTransaction())
    }

    fun addCarGoods(goodData:List<OrderGoodsInfoVO>?){
        PromptDialog().setConfirmListener(object : PromptDialog.ConfirmHandleListener {
            override fun bindView(dialog: PromptDialog, view: PromptDialog.PromptModel) {
                view.setMsgText(getString(R.string.order_add_car))
                view.setShowCancel(true)
                view.getPromptConfirm().setOnClickListener {
                    dialog.dismiss()
                    var goods = ArrayList<GoodsInfoVO>()
                    goodData?.forEach { item ->
                        goods.add(GoodsInfoVO(
                            goods_id = item.goods_id,
                            goods_sku = GoodsSkuVo(spec_sku_id = item?.spec_sku_id),
                            total_num = item.total_num
                        ))
                    }
                    mMallModel.addCarBatch(goods)
                }
            }
        }).onShow(childFragmentManager.beginTransaction())
    }

    fun addSuccess(){
        PromptDialog().setConfirmListener(object : PromptDialog.ConfirmHandleListener {
            override fun bindView(dialog: PromptDialog, view: PromptDialog.PromptModel) {
                view.setMsgText(getString(R.string.added_cart))
                view.setShowCancel(true)
                view.setConfirmText(getString(R.string.go_to_car))
                view.getPromptConfirm().setOnClickListener {
                    dialog.dismiss()
                    SPUtils.getInstance().put("home",2)
                    startActivity(MainActivity::class.intent)
                }
            }
        }).onShow(childFragmentManager.beginTransaction())
    }

    override fun onStart() {
        super.onStart()
    }

}